package cn.com.wanywhn.a2017_04_02_bmob_brvah;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.util.AbstractDrawerImageLoader;
import com.mikepenz.materialdrawer.util.DrawerImageLoader;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Adapter.CategroyAdapter;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Bean.MyUser;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Data.CategroyData;
import cn.com.wanywhn.a2017_04_02_bmob_brvah.Data.CategroyDataSection;

public class MainActivity extends BaseActivityToolBar implements
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    RecyclerView rv;
    CategroyAdapter adapter;
    List<CategroyDataSection> data;
    MyUser muser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        muser = BmobUser.getCurrentUser(MyUser.class);
        if (muser != null) {
            initDrawer();
            initAdapter();
            initViews();
        }
        if (muser == null) {
            startActivity(new Intent(this, LoginActivity.class));
            Toast.makeText(this, "验证已过期，请重新登陆", Toast.LENGTH_SHORT).show();
            this.finish();
        }
//        setVisiableToolBar();
    }

    private void initAdapter() {
        data = CategroyData.getdata();
        adapter = new CategroyAdapter(
                R.layout.categroyitem, R.layout.def_section_head, data);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemChildClickListener(this);

    }

    private void initViews() {
        rv = (RecyclerView) findViewById(R.id.recv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(adapter);


    }

    //已经将头像链接存入用户信息内。
    //将头像链接地址存入了文件，可以考虑其他方法
//    public void writeFileData(String filename, String message) {
//        try {
//            File file = new File(filename);
//            if (!file.exists()) {
//                file.createNewFile();
//            }
//            FileOutputStream fileOutputStream = openFileOutput(filename, MODE_PRIVATE);
//            byte[] bytes = message.getBytes();
//            fileOutputStream.write(bytes);
//            fileOutputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public String readFileData(String filename) {
//        String res = null;
//        try {
//            FileInputStream inputStream = openFileInput(filename);
//            int length = inputStream.available();
//            byte[] buffer = new byte[length];
//            inputStream.read(buffer);
//            res = new String(buffer);
//            inputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return res;
//    }

    void initDrawer() {
        String url = getIntent().getStringExtra("url");
        if (url != null) {
            muser.setPicUrl(url);
            MyUser tmp=new MyUser();
            tmp.setPicUrl(url);
            tmp.update(muser.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        System.out.println("更新头像成功");
                    }else {
                        Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
//            writeFileData("ImgUrl", url);
        } else {
//            url = readFileData("ImgUrl");
            url=muser.getPicUrl();
        }
        final String URL = url;
        //加载图片
        DrawerImageLoader imageLoader = DrawerImageLoader.init(new AbstractDrawerImageLoader() {
            @Override
            public void set(ImageView imageView, Uri uri, Drawable placeholder) {
                Picasso.with(imageView.getContext()).load(URL).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Picasso.with(imageView.getContext()).cancelRequest(imageView);
            }
        });
        //初始化Header
        AccountHeader header = new AccountHeaderBuilder()
                .withActivity(this)
                //TODO 背景可以自定义
                .withHeaderBackground(R.mipmap.back)
                .addProfiles(new ProfileDrawerItem().withIcon(url)
                        .withName(muser.getUsername()).withEmail(muser.getEmail()))
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean current) {
                        // TODO: 17-4-6 个人信息设置
                        Intent mIntent = new Intent(MainActivity.this, Info_edit.class);
                        mIntent.putExtra("url", URL);
                        startActivity(mIntent);
                        return false;
                    }
                }).build();

        //TODO 增加策划菜单栏内容
        PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.library_materialdrawer_owner);
        PrimaryDrawerItem itemSetting = new PrimaryDrawerItem().withIdentifier(10).withName("设置").withIcon(R.drawable.main_setting);
        SecondaryDrawerItem itemExit = new SecondaryDrawerItem().withIdentifier(99).withName("EXIT");
        Drawer mDrawer = new DrawerBuilder().withActivity(this).addDrawerItems(
                item1,
                new DividerDrawerItem(),
                itemSetting,
                new DividerDrawerItem(),
                itemExit

        ).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
            @Override
            public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();

                switch ((int) drawerItem.getIdentifier()) {
                    case 99:
                        MainActivity.this.finish();
                        BmobUser.logOut();
                        break;
                    case 1:
                        break;
                    case 10:
                        // TODO: 17-4-6 设置页面

                }

                return true;
            }
        }).withToolbar(toolbar).withAccountHeader(header).build();
    }

    //RecycleView子节点的监听器
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        CategroyDataSection cds = data.get(position);
        if (cds.isHeader) {
            Toast.makeText(this, position + "Is Header", Toast.LENGTH_SHORT).show();
        } else {
            switch (data.get(position).t.getId()) {
                case 10:
                    Intent intent = new Intent(MainActivity.this, PostListViewer_.class);
                    intent.putExtra("to", "线上提问");
                    startActivity(intent);
                    break;
                case 15:
            }
        }
    }

    //RV子节点的子节点的监听器
    @Override
    public boolean onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Toast.makeText(this, "" + position + ":" + view.getId(), Toast.LENGTH_SHORT).show();
        return true;
    }
}
